package com.github.xaidanwang.mybatisshardingjdbc.demo.config;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.LinkedHashSet;

public class TimeRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {
	private static DateTimeFormatter dateformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
	private static DateTimeFormatter dateformat2 = DateTimeFormatter.ofPattern("yyyyMM");
	private static ZoneId zoneId = ZoneId.systemDefault();
	@Override
	public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<String> shardingValue) {
		// 表的集合
		Collection<String> result = new LinkedHashSet<String>();
		// 计算开始时间与结束时间相差几个月，不支持跨年
		String startShardingKey = shardingValue.getValueRange().upperEndpoint();
		String endShardingKey = shardingValue.getValueRange().upperEndpoint();
		LocalDateTime startTime = LocalDateTime.parse(startShardingKey,dateformat);
		LocalDateTime endTime = LocalDateTime.parse(endShardingKey,dateformat);
		LocalDate start = startTime.atZone(zoneId).toLocalDate();
		LocalDate end = endTime.atZone(zoneId).toLocalDate();
		int totalMonth = (end.getYear() - start.getYear())*12 + (start.getMonthValue() - end.getMonthValue());
		// 返回命中的表明集合
		for (int i = 0; i <= totalMonth; i++) {
			StringBuffer tableName = new StringBuffer();
			tableName.append(shardingValue.getLogicTableName())
					.append("_").append(start.format(dateformat2));
			result.add(tableName.toString());
			start = start.plusMonths(1);
		}
		return result;
	}
}
